import app from '../bootstrap';

import UrlPattern from 'url-pattern';

let routerInstance: any = null;
let routerInstanceMehthods: any[] = [];

export function Router(path: any) {
    // tslint:disable-next-line:only-arrow-functions
    return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        // @ts-ignore

        // console.log("====target====>", target);
        target.prototype.app = app;
        routerInstance = new target(target.prototype.app.context);
        routerInstance.app.use(async (ctx: any, next: any) => {
            routerInstanceMehthods.map(async (methodItem) => {
                var currentPath = ctx.request.url;
                var _routerPath = path + methodItem.path;
                var patter = new UrlPattern(_routerPath);
                // console.log("====_routerPath====>",_routerPath)
                // console.log("==currentPath======>",currentPath)
                // console.log("===patter.match(currentPath)=====>",patter.match(currentPath))
                if (patter.match(currentPath)) {
                    routerInstance.ctx = ctx;
                    routerInstance.next = next;
                    return await methodItem.descriptor.value.call(routerInstance);
                }
            });
        });

    };
}

export function Get(path: any) {
    return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        // routerInstance.ctx.request.path
        routerInstanceMehthods.push({
            path,
            propertyKey,
            descriptor
        });
    };
}